package com.lxq.live.util;

import com.lxq.live.dao.VideoRowRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.io.*;
import java.time.Duration;

@Component
public class VideoBarrageRepository {

    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    VideoRowRepository videoRowRepository;

    public String barrageCenter(String videoUuid) {
        var opsKV = stringRedisTemplate.opsForValue();
        var barrageStr = opsKV.get("barrage_" + videoUuid);
        if (barrageStr != null) {
            opsKV.set("barrage_" + videoUuid, barrageStr, Duration.ofMinutes(10));
            return opsKV.get("barrage_" + videoUuid);
        }
        barrageStr = queryBarrage(videoUuid);//需要优化
        if (barrageStr.equals("")) {
            System.out.println("获取不到JSON数据");
            return "";
        }
//        if (stringRedisTemplate==null){
//            System.out.println("stringRedisTemplate为空");
//            return "";
//        }
//        if (stringRedisTemplate.opsForValue().get("barrage_"+videoUuid)==null){
//            stringRedisTemplate.opsForValue().set("barrage_"+videoUuid,barrageStr, Duration.ofMinutes(1));
//        }
        opsKV.set("barrage_" + videoUuid, barrageStr, Duration.ofMinutes(10));
        return opsKV.get("barrage_" + videoUuid);
    }

    public void updateBarrage(String videoUuid) {
        var opsKV = stringRedisTemplate.opsForValue();
        opsKV.set("barrage_" + videoUuid, queryBarrage(videoUuid), Duration.ofMinutes(10));
    }

//    private String getBarrageFromFile() {
//        File file = new File("D:/springdemo/lxqlive/src/main/resources/static/弹幕.json");
//        if (!file.exists()) return "";
//        StringBuilder stringBuilder = new StringBuilder();
//        try (
//                FileReader fileReader = new FileReader(file);
//                BufferedReader bufferedReader = new BufferedReader(fileReader)
//        ) {
//            var lineStr = "";
//            while ((lineStr = bufferedReader.readLine()) != null) {
//                stringBuilder.append(lineStr);
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return stringBuilder.toString();
//    }

    private String queryBarrage(String videoUuid) {
        return videoRowRepository.getVideoBarrage(videoUuid);
    }
}
